<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>my redux</title>
  </head>
  <body>
    <button id="increment">+1</button>
    <span id="box">0</span>
    <button id="decrement">-1</button>
    <script src="myRedux.js"></script>
    <script src="middlewares/logger.js"></script>
    <script src="middlewares/thunk.js"></script>
    <script>
      function enhancer(createStore) {
        return function (reducer, preloadedState) {
          var store = createStore(reducer, preloadedState);
          var dispatch = store.dispatch;
          function _dispatch(action) {
            if (typeof action === "function") {
              return action(dispatch);
            }
            dispatch(action);
          }
          return {
            ...store,
            dispatch: _dispatch,
          };
        };
      }

      // function reducer(state, action) {
      function counterReducer(state, action) {
        switch (action.type) {
          case "increment":
            return state + 1;
          case "decrement":
            return state - 1;
          default:
            return state;
        }
      }
      
      var rootReducer = combineReducers({counter: counterReducer})
      
      // 创建store
      // var store = createStore(reducer, 0, enhancer);
      // var store = createStore(reducer, 100, applyMiddleware(logger, thunk));
      var store = createStore(rootReducer, {counter: 100}, applyMiddleware(logger, thunk));

      // 注册订阅者
      store.subscribe(function () {
        // 获取最新的状态
        console.log(store.getState());
        // document.getElementById("box").innerHTML = store.getState();
        document.getElementById("box").innerHTML = store.getState().counter;
      });

      var actions = bindActionCreators(
        { increment, decrement },
        store.dispatch
      );

      function increment() {
        return { type: "increment" };
      }

      function decrement() {
        return { type: "decrement" };
      }

      // 获取加按钮
      document.getElementById("increment").onclick = function () {
        // 触发action 让数值加1
        // logger -> thunk -> reducer
        // store.dispatch({ type: "increment" });

        actions.increment()

        // 测试使用enhancer，做增强版的store验证
        // store.dispatch(function(dispatch) {
        //   setTimeout(function() {
        //     dispatch({ type: "increment" })
        //   }, 1000)
        // })
      };

      // 获取减按钮
      document.getElementById("decrement").onclick = function () {
        // 触发action 让数值减一
        // store.dispatch({ type: "decrement" });
        actions.decrement()
      };
    </script>
  </body>
</html>
